package com.zk.controller.BasicController;

import com.zk.entity.ResultDto;
import com.zk.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = {"用户登录Controller"})
@RestController
public class loginController {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "转发到登录页面", tags = {"我重置了tagLogin页面"})
    @GetMapping("/toLoginView")
    public String toLoginView() {
        return "login";
    }

    @ApiOperation(tags = {"登录"}, notes = "用户密码不能为空", value = "登录后进行验证")

    @ApiImplicitParam(name = "params", value = "传入用户名与密码", dataType = "Map", paramType = "body")
    @PostMapping("/login")
    public ResultDto<User> toLogin(@RequestBody Map<String,String> params
            , HttpSession session
    ) {
        String username = params.get("username");
        String password = params.get("password");

        //参数验证
        ResultDto<User> resultDto = new ResultDto<>();

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            System.out.println("我在执行登陆前==============");
            subject.login(token);//执行登陆的方法
            session.setAttribute("loginUser", username);//设置session
            redisTemplate.opsForHash().put(username,"login",new Date().toString());
            redisTemplate.expire(username,10, TimeUnit.MINUTES);

            resultDto.setCode(200);
            resultDto.setMsg("用户登录成功");


        }
        catch (IncorrectCredentialsException ice) {
            resultDto.setCode(500);
            resultDto.setMsg("用户名或密码不正确");
        } catch (DisabledAccountException uae) {
            resultDto.setCode(500);
            resultDto.setMsg("用户名以禁用");

        } catch (UnknownAccountException uae) {

            resultDto.setCode(500);
            resultDto.setMsg("未知账户");
            System.out.println("=================>>>我进入了未知用户");

        } catch (ExcessiveAttemptsException eae) {

            resultDto.setCode(500);
            resultDto.setMsg("用户名或密码错误次数太多");
        } catch (Exception ae) {

            resultDto.setCode(500);
            resultDto.setMsg("验证未通过");
        }
        return resultDto;
    }

    //tag相当于在Swagger里面生成另一个标签
    @ApiOperation(value = "未授权")
    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized() {
        return "未经授权禁止访问";

    }
}
